package com.hframe.database;

import com.sun.istack.internal.NotNull;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/12/25.
 */

public class Sql {
    protected final StringBuffer sql = new StringBuffer();
    protected final Map<String, Object> params = new HashMap<>();
    protected SqlTemplate template = null;

    public Sql(@NotNull SqlTemplate template) {
        this.template = template;
    }

    public Sql(String sql) {
        this.sql.append(sql);
        template = null;
    }

    public Sql add(String sql) {
        this.sql.append(sql);
        template = null;
        return this;
    }

    public Sql set(@NotNull SqlTemplate template) {
        this.sql.setLength(0);
        this.sql.append(sql);
        this.template = template;
        return this;
    }

    public Sql addParam(String name, Object val) {
        this.params.put(name, val);
        return this;
    }

    public Map<String, Object> getParams() {
        return this.params;
    }

    public void clearParams() {
        this.params.clear();
    }

    @Override
    public String toString() {
        if (null != template) {
            return template.toString();
        }
        return sql.toString();
    }

    public SqlTemplate getTemplate() {
        if (null == template) {
            template = new SqlTemplate(sql.toString());
        }
        return template;
    }
}
